from django.http import HttpResponseForbidden


class RequestHeadersMiddleware:
    """输出当前请求的请求头信息"""

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # 在请求处理前输出请求头
        print("\n=== 请求头信息 ===")
        for header, value in request.headers.items():
            print(f"{header}: {value}")
        print("================\n")

        response = self.get_response(request)
        return response


class LoginRequiredMiddleware:
    """验证用户是否已登录"""

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # 定义需要登录的URL路径前缀
        protected_paths = ['/dashboard/', '/profile/', '/settings/']

        # 检查当前路径是否需要验证
        if any(request.path.startswith(path) for path in protected_paths):
            if not request.user.is_authenticated:
                return HttpResponseForbidden("请先登录以访问此页面")

        response = self.get_response(request)
        return response


class ClientIPMiddleware:
    """输出当前请求的IP地址"""

    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        # 获取客户端IP地址
        x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
        if x_forwarded_for:
            ip = x_forwarded_for.split(',')[0]
        else:
            ip = request.META.get('REMOTE_ADDR')

        print(f"\n客户端IP地址: {ip}\n")
        request.client_ip = ip  # 将IP存储在request对象中以供后续使用

        response = self.get_response(request)
        return response
